<template>
  <div class="my-content-page">
    <div class="page-container">
      <!-- 页面头部 -->
      <div class="page-header">
        <div class="header-left">
          <h1 class="gradient-text">我的内容</h1>
          <p>管理你的所有创作内容</p>
        </div>
        <div class="header-right">
          <el-button 
            type="primary" 
            @click="$router.push('/create')"
            class="create-btn"
          >
            <el-icon><Plus /></el-icon>
            发布新内容
          </el-button>
        </div>
      </div>
      
      <!-- 统计信息 -->
      <div class="stats-cards">
        <div class="stat-card">
          <div class="stat-number">{{ totalContents }}</div>
          <div class="stat-label">总内容数</div>
        </div>
        <div class="stat-card">
          <div class="stat-number">{{ totalLikes }}</div>
          <div class="stat-label">总点赞数</div>
        </div>
        <div class="stat-card">
          <div class="stat-number">{{ totalComments }}</div>
          <div class="stat-label">总评论数</div>
        </div>
        <div class="stat-card">
          <div class="stat-number">{{ totalViews }}</div>
          <div class="stat-label">总浏览量</div>
        </div>
      </div>
      
      <!-- 筛选和操作栏 -->
      <div class="toolbar">
        <div class="filters">
          <el-select 
            v-model="statusFilter" 
            placeholder="状态筛选"
            @change="loadContents"
          >
            <el-option label="全部" value="" />
            <el-option label="已发布" value="published" />
            <el-option label="草稿" value="draft" />
          </el-select>
          
          <el-select 
            v-model="typeFilter" 
            placeholder="类型筛选"
            @change="loadContents"
          >
            <el-option label="全部类型" value="" />
            <el-option label="图片" value="IMAGE" />
            <el-option label="视频" value="VIDEO" />
            <el-option label="文档" value="DOCUMENT" />
          </el-select>
          
          <el-input
            v-model="searchKeyword"
            placeholder="搜索标题..."
            @keyup.enter="loadContents"
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="batch-actions" v-if="selectedContents.length > 0">
          <span class="selected-count">已选择 {{ selectedContents.length }} 项</span>
          <el-button @click="batchDelete" type="danger" size="small">
            批量删除
          </el-button>
        </div>
      </div>
      
      <!-- 内容列表 -->
      <div class="content-list">
        <!-- 加载状态 -->
        <div v-if="loading && contents.length === 0" class="loading-wrapper">
          <el-skeleton 
            v-for="i in 6" 
            :key="i" 
            animated 
            class="content-skeleton"
          >
            <template #template>
              <el-skeleton-item variant="image" style="width: 80px; height: 80px;" />
              <div style="flex: 1; margin-left: 16px;">
                <el-skeleton-item variant="h3" style="width: 40%" />
                <el-skeleton-item variant="text" style="width: 60%" />
                <el-skeleton-item variant="text" style="width: 30%" />
              </div>
            </template>
          </el-skeleton>
        </div>
        
        <!-- 内容项 -->
        <div 
          v-for="content in contents" 
          :key="content.id" 
          class="content-item xhs-card"
        >
          <div class="item-checkbox">
            <el-checkbox 
              v-model="selectedContents" 
              :value="content.id"
            />
          </div>
          
          <div class="item-cover" @click="goToDetail(content.id)">
            <img 
              v-if="content.fileUrl && content.type === 'IMAGE'" 
              :src="content.fileUrl" 
              :alt="content.title"
              class="cover-image"
            />
            <div v-else class="cover-placeholder">
              <el-icon>
                <VideoPlay v-if="content.type === 'VIDEO'" />
                <Document v-else />
              </el-icon>
            </div>
          </div>
          
          <div class="item-content" @click="goToDetail(content.id)">
            <h3 class="content-title">{{ content.title }}</h3>
            <p class="content-description">{{ content.description }}</p>
            
            <div class="content-meta">
              <span class="content-type">{{ getTypeLabel(content.type) }}</span>
              <span class="content-status" :class="content.published ? 'published' : 'draft'">
                {{ content.published ? '已发布' : '草稿' }}
              </span>
              <span class="content-time">{{ formatTime(content.createdAt) }}</span>
            </div>
            
            <div class="content-stats">
              <span class="stat-item">
                <el-icon><View /></el-icon>
                {{ content.viewCount || 0 }}
              </span>
              <span class="stat-item">
                <el-icon><StarFilled /></el-icon>
                {{ content.likeCount || 0 }}
              </span>
              <span class="stat-item">
                <el-icon><ChatLineRound /></el-icon>
                {{ content.commentCount || 0 }}
              </span>
            </div>
          </div>
          
          <div class="item-actions">
            <el-button 
              @click="editContent(content)" 
              type="primary" 
              text
              size="small"
            >
              编辑
            </el-button>
            <el-button 
              @click="togglePublish(content)" 
              type="success" 
              text
              size="small"
            >
              {{ content.published ? '取消发布' : '发布' }}
            </el-button>
            <el-button 
              @click="deleteContent(content)" 
              type="danger" 
              text
              size="small"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="total > 0" class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadContents"
          @current-change="loadContents"
        />
      </div>
      
      <!-- 空状态 -->
      <div v-if="!loading && contents.length === 0" class="empty-state">
        <el-empty description="暂无内容">
          <el-button type="primary" @click="$router.push('/create')">
            发布第一个内容
          </el-button>
        </el-empty>
      </div>
    </div>
    
    <!-- 编辑对话框 -->
    <ContentEditDialog
      v-if="editingContent"
      :content="editingContent"
      :visible="editDialogVisible"
      @close="closeEditDialog"
      @updated="handleContentUpdated"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getMyContents, deleteContent as deleteContentApi, updateContent } from '@/api/content'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { 
  Plus, 
  Search, 
  VideoPlay, 
  Document, 
  View, 
  StarFilled, 
  ChatLineRound 
} from '@element-plus/icons-vue'

const router = useRouter()

const contents = ref([])
const loading = ref(false)
const selectedContents = ref([])
const editingContent = ref(null)
const editDialogVisible = ref(false)

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const statusFilter = ref('')
const typeFilter = ref('')
const searchKeyword = ref('')

// 统计数据
const totalContents = computed(() => contents.value.length)
const totalLikes = computed(() => contents.value.reduce((sum, item) => sum + (item.likeCount || 0), 0))
const totalComments = computed(() => contents.value.reduce((sum, item) => sum + (item.commentCount || 0), 0))
const totalViews = computed(() => contents.value.reduce((sum, item) => sum + (item.viewCount || 0), 0))

// 加载我的内容
const loadContents = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value
    }
    
    if (statusFilter.value) {
      params.published = statusFilter.value === 'published'
    }
    if (typeFilter.value) {
      params.type = typeFilter.value
    }
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value
    }
    
    const res = await getMyContents(params)
    contents.value = res.data?.content || []
    total.value = res.data?.totalElements || 0
  } catch (error) {
    console.error('加载内容失败:', error)
    ElMessage.error('加载内容失败')
  } finally {
    loading.value = false
  }
}

// 跳转到详情页
const goToDetail = (id) => {
  router.push(`/content/${id}`)
}

// 获取类型标签
const getTypeLabel = (type) => {
  const typeMap = {
    'IMAGE': '图片',
    'VIDEO': '视频',
    'DOCUMENT': '文档'
  }
  return typeMap[type] || type
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 编辑内容
const editContent = (content) => {
  editingContent.value = { ...content }
  editDialogVisible.value = true
}

// 关闭编辑对话框
const closeEditDialog = () => {
  editDialogVisible.value = false
  editingContent.value = null
}

// 处理内容更新
const handleContentUpdated = () => {
  loadContents()
  closeEditDialog()
}

// 切换发布状态
const togglePublish = async (content) => {
  try {
    await updateContent(content.id, {
      published: !content.published
    })
    
    content.published = !content.published
    ElMessage.success(content.published ? '发布成功' : '取消发布成功')
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 删除内容
const deleteContent = async (content) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除内容"${content.title}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await deleteContentApi(content.id)
    ElMessage.success('删除成功')
    loadContents()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedContents.value.length} 个内容吗？此操作不可恢复。`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    for (const id of selectedContents.value) {
      await deleteContentApi(id)
    }
    
    selectedContents.value = []
    ElMessage.success('批量删除成功')
    loadContents()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

onMounted(() => {
  loadContents()
})
</script>

<style scoped lang="scss">
.my-content-page {
  min-height: 100vh;
  background-color: $bg-light;
  padding: $spacing-lg 0;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 $spacing-lg;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: $spacing-xl;
  
  .header-left {
    h1 {
      font-size: $font-size-xxl * 1.2;
      margin-bottom: $spacing-sm;
    }
    
    p {
      color: $text-secondary;
      font-size: $font-size-lg;
    }
  }
  
  .create-btn {
    border-radius: $border-radius-large;
  }
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: $spacing-lg;
  margin-bottom: $spacing-xl;
  
  .stat-card {
    background: $bg-white;
    padding: $spacing-lg;
    border-radius: $border-radius-large;
    box-shadow: $shadow-light;
    text-align: center;
    
    .stat-number {
      font-size: $font-size-xxl;
      font-weight: bold;
      color: $primary-color;
      margin-bottom: $spacing-sm;
    }
    
    .stat-label {
      color: $text-secondary;
      font-size: $font-size-sm;
    }
  }
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: $spacing-lg;
  background: $bg-white;
  padding: $spacing-md;
  border-radius: $border-radius-large;
  box-shadow: $shadow-light;
  
  .filters {
    display: flex;
    gap: $spacing-md;
    align-items: center;
  }
  
  .batch-actions {
    display: flex;
    align-items: center;
    gap: $spacing-md;
    
    .selected-count {
      color: $text-secondary;
      font-size: $font-size-sm;
    }
  }
}

.content-list {
  .loading-wrapper {
    .content-skeleton {
      background: $bg-white;
      border-radius: $border-radius-large;
      padding: $spacing-md;
      margin-bottom: $spacing-md;
      display: flex;
      align-items: center;
    }
  }
  
  .content-item {
    display: flex;
    align-items: center;
    padding: $spacing-md;
    margin-bottom: $spacing-md;
    background: $bg-white;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: $shadow-medium;
    }
    
    .item-checkbox {
      margin-right: $spacing-md;
    }
    
    .item-cover {
      width: 80px;
      height: 80px;
      border-radius: $border-radius-medium;
      overflow: hidden;
      margin-right: $spacing-md;
      flex-shrink: 0;
      
      .cover-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .cover-placeholder {
        width: 100%;
        height: 100%;
        background: $bg-light;
        display: flex;
        align-items: center;
        justify-content: center;
        color: $text-light;
        
        .el-icon {
          font-size: $spacing-lg;
        }
      }
    }
    
    .item-content {
      flex: 1;
      
      .content-title {
        font-size: $font-size-md;
        font-weight: 600;
        color: $text-primary;
        margin-bottom: $spacing-xs;
        line-height: 1.4;
      }
      
      .content-description {
        font-size: $font-size-sm;
        color: $text-secondary;
        margin-bottom: $spacing-sm;
        line-height: 1.5;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .content-meta {
        display: flex;
        gap: $spacing-md;
        margin-bottom: $spacing-sm;
        font-size: $font-size-xs;
        
        .content-type {
          color: $text-light;
        }
        
        .content-status {
          padding: 2px 6px;
          border-radius: $border-radius-small;
          
          &.published {
            background: $success-color;
            color: white;
          }
          
          &.draft {
            background: $warning-color;
            color: white;
          }
        }
        
        .content-time {
          color: $text-light;
        }
      }
      
      .content-stats {
        display: flex;
        gap: $spacing-lg;
        
        .stat-item {
          display: flex;
          align-items: center;
          gap: $spacing-xs;
          font-size: $font-size-xs;
          color: $text-light;
          
          .el-icon {
            font-size: $font-size-sm;
          }
        }
      }
    }
    
    .item-actions {
      display: flex;
      flex-direction: column;
      gap: $spacing-sm;
    }
  }
}

.pagination {
  margin-top: $spacing-xl;
  display: flex;
  justify-content: center;
}

.empty-state {
  margin-top: $spacing-xxl;
}

// 响应式设计
@media (max-width: $breakpoint-md) {
  .page-container {
    padding: 0 $spacing-md;
  }
  
  .page-header {
    flex-direction: column;
    gap: $spacing-md;
    text-align: center;
  }
  
  .toolbar {
    flex-direction: column;
    gap: $spacing-md;
  }
  
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: $breakpoint-sm) {
  .page-container {
    padding: 0 $spacing-sm;
  }
  
  .content-item {
    .item-actions {
      flex-direction: row;
      gap: $spacing-xs;
    }
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
}
</style> 